<template>
  <el-card class="edit-card" shadow="never">
    <div slot="header" class="clearfix">
      <span class="title">{{ title }}</span>
      <i style="float: right;cursor: pointer;user-select: none;" v-if="showEdit" v-show="!isEdit" @click="editText" class="el-icon-edit"></i>
    </div>
    <div class="edit-card-content" ref="block" v-if="!refresh" style="white-space: pre-wrap" :contenteditable="isEdit" @blur="changeText">{{content}}</div>
    <div class="edit-footer" v-show="isEdit">
      <el-button size="small" @click="editText">Cancel</el-button>
      <el-button size="small" type="primary" @click="saveText">Save</el-button>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'editBlock',
  props: ['title', 'content', 'showEdit'],
  data () {
    return {
      isEdit: false,
      updateText: null,
      refresh: false
    }
  },
  watch: {
    content () {
      this.refresh = true
      this.$nextTick(() => {
        this.refresh = false
      })
    }
  },
  methods: {
    editText () {
      if (this.isEdit) {
        this.isEdit = false
        this.$refs['block'].innerHTML = this.content || ''
        this.$emit('update:content', this.content)
      } else {
        this.isEdit = true
      }
    },
    changeText (e) {
      this.updateText = e.target.innerText
    },
    saveText () {
      this.$emit('update:content', this.updateText)
      this.$emit('save')
      this.isEdit = false
    }
  }
}
</script>

<style scoped lang="scss">
.edit-card{
  //::v-deep .el-card__header{
  //  //line-height: 40px;
  //  //padding: 0 12px;
  //  i {
  //    line-height: 40px;
  //  }
  //}
  ::v-deep .el-card__body{
    padding: 0;
  }
}
.edit-card-content {
  padding: 20px;
  word-wrap:break-word;
}
.edit-card-content[contenteditable="true"] {
  border: 1px solid #0043CE;
}
.edit-footer {
  //text-align: right;
  height: 48px;
  padding-right: 12px;
  display: flex;
  align-items: center;
  justify-content: right;
}
.title {
  font-weight: bold;
}
</style>
